package com.wang.myblog.service.impl;

import com.wang.myblog.common.PageResponse;
import com.wang.myblog.common.PageResult;
import com.wang.myblog.controller.common.UploadController;
import com.wang.myblog.entity.*;
import com.wang.myblog.mapper.*;
import com.wang.myblog.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    ArticleMapper articleMapper;

    @Autowired
    ArticleTagMapper articleTagMapper;

    @Autowired
    KindMapper kindMapper;

    @Autowired
    TagMapper tagMapper;

    @Autowired
    CommentMapper commentMapper;

    @Override
    public boolean insert(Article article) {
        if (articleMapper.insert(article) == 1) {
            return true;
        }
        return false;
    }

    @Override
    public boolean deleteById(Integer id) {
        Article article=articleMapper.queryById(id);
        if (articleMapper.deleteById(id) == 1) {
            UploadController.deleteCommonImg(article.getImg());
            articleMapper.deleteById(id);
            articleTagMapper.deleteById(id);
            commentMapper.deleteByArticleId(id);
            return true;
        }
        return false;
    }

    @Override
    public Article queryById(Integer id) {
        Article article;
        article=articleMapper.queryById(id);
        List<Tag> tags=articleTagMapper.queryByArticleId(id);
        //System.out.println(article);
        article.setTags(tags);
        article.setKind(kindMapper.queryById(article.getKindId()));
        article.setComment(commentMapper.getCountByArticleId(id));
        return article;
    }

    @Override
    public boolean update(Article article) {
        Article article1=articleMapper.queryById(article.getId());
        if (articleMapper.update(article) == 1) {
            if(!article.getImg().equals(article1.getImg())){
                UploadController.deleteCommonImg(article1.getImg());
            }
            return true;
        }
        return false;
    }

    @Override
    public List<Article> queryByStatus(Integer status) {
        List<Article> articles= articleMapper.queryByStatus(status);
        articles.forEach(article -> {
            article.setComment(commentMapper.getCountByArticleId(article.getId()));
            article.setTags(articleTagMapper.queryByArticleId(article.getId()));
            article.setKind(kindMapper.queryById(article.getKindId()));
        });
        return articles;
    }

    public boolean update(Integer id, String title, String content, List<Integer> tagIdList, Integer kindId, String introduce, Integer status,String img) {
        // 首先获取文章
        Article article = articleMapper.queryById(id);
        article.setTitle(title);
        article.setContent(content);
        article.setKindId(kindId);
        if(!article.getImg().equals(img)){
            UploadController.deleteCommonImg(article.getImg());
            article.setImg(img);
        }
        if ("".equals(introduce)) {
            // 摘要为空
            String s = content.replaceAll(" ", "");
            s = s.replaceAll("#", "");
            s = s.replaceAll("\n", "");
            if (s.length() > 100) {
                introduce = s.substring(0, 100);
            }
        }
        article.setIntroduce(introduce);
        article.setStatus(status);
//        // 如果原来的文章发布时间为空
//        if (ObjectUtils.isEmpty(article.getPublishTime())){
//            article.setPublishTime(new Date());
//        }
        article.setRecentEdit(new Date());
        articleMapper.update(article);

        articleTagMapper.deleteById(id);
        for(int i=0;i<tagIdList.size();i++){
            articleTagMapper.insert(new ArticleTag(id,tagIdList.get(i)));
        }
        return true;

    }

    public Integer publish(String title, String content, String introduce, Integer status,String img,Integer kindId,List<Integer> tagIdList) {
        Article article = new Article();
        article.setTitle(title);
        article.setContent(content);
        article.setStatus(status);
        article.setComment(0);
        article.setImg(img);
        article.setKindId(kindId);
        article.setKind(kindMapper.queryById(kindId));
//        List<Tag> tags=new ArrayList<>();
        //System.out.println(article.getId());
//        for(int i=0;i<tagIdList.size();i++){
//            articleTagMapper.insert(new ArticleTag(article.getId(),tagIdList.get(i)));
//            tags.add(tagMapper.queryById(tagIdList.get(i)));
//        }
//        article.setTags(tags);
//        System.out.println(article.getTags());
        if (status != 0) {
            article.setPublishTime(new Date());
        }
        article.setRecentEdit(new Date());
        article.setReadCount(0);
        if ("".equals(introduce)) {
            // 摘要为空
            introduce = content.length() > 100 ? content.substring(0, 100) : content;
        }
        article.setIntroduce(introduce);
        articleMapper.insert(article);
        for(int i=0;i<tagIdList.size();i++){
            articleTagMapper.insert(new ArticleTag(article.getId(),tagIdList.get(i)));
//            tags.add(tagMapper.queryById(tagIdList.get(i)));
        }



        return article.getId();
    }


    public PageResponse queryByPageAndStatus(Integer draw,Integer start, Integer limit, Integer status,String searchMsg){
    //page是当前页面，mapper里面的start是数据库开始行的索引（从0开始）
//        List<Article> articleList=articleMapper.queryByPageAndStatus((page-1)*limit,limit,status);
         List<Article> articleList=articleMapper.queryByPageAndStatus(start,limit,status,searchMsg);
         articleList.forEach(article -> {
             article.setKind(kindMapper.queryById(article.getKindId()));
             article.setTags(articleTagMapper.queryByArticleId(article.getId()));
             article.setComment(commentMapper.getCountByArticleId(article.getId()));
//            System.out.println(article);
         });
//        System.out.println("进入了service层"+"searchMsg为");
          Integer total=articleMapper.getCountByStatus(status,searchMsg);
//        System.out.println("service total:"+total);
         return new PageResponse(draw,total,total,articleList);
}

    public Integer getCountByStatus(Integer status,String searchMsg){
        return articleMapper.getCountByStatus(status,searchMsg);
    }

    public boolean clearRecyleBin(){
        List<Article> list=articleMapper.queryByStatus(2);
        list.forEach(article -> {
            UploadController.deleteCommonImg(article.getImg());
            articleMapper.deleteById(article.getId());
            articleTagMapper.deleteById(article.getId());
            commentMapper.deleteByArticleId(article.getId());
        });
        return true;
    }

    public List<Article> queryPublishedArticleOrderByPublishTime(Integer page){
        List<Article> articles=articleMapper.queryPublishedArticleOrderByPublishTime((page-1)*10,10);
        articles.forEach(article -> {
            article.setKind(kindMapper.queryById(article.getKindId()));
            article.setTags(articleTagMapper.queryByArticleId(article.getId()));
            article.setComment(commentMapper.getCountByArticleId(article.getId()));
        });
        return articles;
    }

    public List<Article> queryOrderByReadCount(){
        List<Article> articleList=articleMapper.queryOrderByReadCount();
        articleList.forEach(article -> {
            article.setKind(kindMapper.queryById(article.getKindId()));
            article.setTags(articleTagMapper.queryByArticleId(article.getId()));
            article.setComment(commentMapper.getCountByArticleId(article.getId()));
        });
        return articleList;
    }

    @Override
    public List<Archive> getArchive() {
        return articleMapper.getArchive();
    }

    @Override
    public List<Article> queryPublishedArticleByTagId(Integer tagId, Integer page) {
        List<Article> articles=articleMapper.queryPublishedArticleByTagId(tagId,(page-1)*10,10);
        articles.forEach(article -> {
            article.setKind(kindMapper.queryById(article.getKindId()));
            article.setTags(articleTagMapper.queryByArticleId(article.getId()));
            article.setComment(commentMapper.getCountByArticleId(article.getId()));
        });
        return articles;
    }

    @Override
    public List<Article> queryPublishedArticleByKindId(Integer kindId, Integer page) {
        List<Article> articles=articleMapper.queryPublishedArticleByKindId(kindId,(page-1)*10,10);
        articles.forEach(article -> {
            article.setKind(kindMapper.queryById(article.getKindId()));
            article.setTags(articleTagMapper.queryByArticleId(article.getId()));
            article.setComment(commentMapper.getCountByArticleId(article.getId()));
        });
        return articles;
    }

    @Override
    public List<Article> queryByDate(Date date,Integer page) {
        List<Article> articles= articleMapper.queryByDate(date,(page-1)*10,10);
        articles.forEach(article -> {
            article.setKind(kindMapper.queryById(article.getKindId()));
            article.setTags(articleTagMapper.queryByArticleId(article.getId()));
            article.setComment(commentMapper.getCountByArticleId(article.getId()));
        });
        return articles;
    }

    @Override
    public List<Article> queryPublishedArticleByMsg(String msg, Integer page) {
        List<Article> articles=articleMapper.queryPublishedArticleByMsg(msg,(page-1)*10,10);
        articles.forEach(article -> {
            article.setKind(kindMapper.queryById(article.getKindId()));
            article.setTags(articleTagMapper.queryByArticleId(article.getId()));
            article.setComment(commentMapper.getCountByArticleId(article.getId()));
        });
        return articles;
    }

    @Override
    public Integer getPublishedArticleCountByDate(String date) {
        List<Archive> archives=articleMapper.getArchive();
        Integer count=0;
        for(Archive archive:archives){
            if (archive.getDate().equals(date)){
                count=archive.getCount();
                break;
            }
        }
        return count;
    }

    @Override
    public Integer getPublishedArticleCountByTagId(Integer tagId) {
        return articleTagMapper.getArticleCountByStatus(tagId,1);
    }

    @Override
    public Integer getPublishedArticleCountByKindId(Integer kindId) {
        return articleMapper.getCountByKindIdAndStatus(kindId,1);
    }

    @Override
    public Integer getPublishedCountByMsg(String msg) {
        return articleMapper.getPublishedCountByMsg(msg);
    }

}
